import os
import re
import shutil
from src.backend.tools.file import create_html
import matplotlib
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor
from PyQt5.QtWidgets import QSizePolicy, QTableWidget, QTableWidgetItem, QPushButton, QScrollArea, QWidget, QGridLayout, \
    QHBoxLayout, QTextEdit, QApplication, QComboBox, QLineEdit, QLabel, QHeaderView
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

MAIN_WINDOW=None
tables={}
def forward(name):
    def wrapper(cls):
        tables[name]=cls
        return cls
    return wrapper
matplotlib.use('TkAgg')
plt.rcParams['font.family'] = 'SimHei'  # 设置默认字体为黑体
# 确保负号等符号能正常显示
plt.rcParams['axes.unicode_minus'] = False
class MplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width,height),dpi=dpi)
        super(MplCanvas, self).__init__(self.fig)
        # # 设置大小策略以允许自由拉伸
        # self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # # 重写 resizeEvent 以便在窗口大小改变时重新调整布局
        # self.resize_event_received = False  # 标记是否已经接收到 resize 事件
class CustomTextEdit(QTextEdit):
    def __init__(self,dir, parent=None):
        super().__init__(parent)
        self.newPath=dir
        self.count=len(os.listdir(dir))

    def update_image_name(self,match):
        # 保存图片到新路径
        old_path = match.group(1)
        with open(old_path,'rb') as f2:
            code=f2.read()
        for path in os.listdir(self.newPath):
            with open(self.newPath+'\\'+path,'rb') as f1:
                if f1.read()==code:
                    return f'src="file:///{self.newPath}\\{path}"'
        name = str(self.count + 1) + '.' + old_path.split('.')[1]
        new_path = os.path.join(self.newPath, name)
        if not os.path.exists(new_path):
            self.count += 1
            # 从临时文件夹复制图片到新路径
            shutil.copy2(old_path, new_path)
        return f'src="file:///{new_path}"'

    def paste(self):
        clipboard= QApplication.clipboard()
        mimeData=clipboard.mimeData()
        if mimeData.hasHtml():
            html = mimeData.html()
            '''
            <span><ruby style="ruby-align:center;" ><span>2</span><rp>(</rp><rt style="font-family:;" >3</rt><rp>)</rp></ruby></span>
            '''
            '''
            mathml = f"""
    <math xmlns="http://www.w3.org/1998/Math/MathML">
      <mfrac>
        <msqrt>
          <mn>{numerator}</mn>
        </msqrt>
        <mn>{denominator}</mn>
      </mfrac>
    </math>
    """
            '''
            pattern = re.compile(r'src="file:///([^"]+)"')
            new_html = pattern.sub(lambda m: self.update_image_name(m), html)
            # if old_path:
            #     shutil.rmtree(os.path.dirname(old_path))
            self.setHtml(new_html)
            return new_html
        else:
            super().paste()  # 如果没有 HTML 内容，使用默认的粘贴行为

    def insertFromMimeData(self, source):
        if source.hasImage():
            # 处理直接粘贴的图像
            from PyQt5.QtGui import QImage
            image = QImage(source.imageData())
            pixmap = QPixmap.fromImage(image)
            self.save_pixmap_and_insert(pixmap)
        elif source.hasHtml():
            self.paste()

        else:
            super().insertFromMimeData(source)
    #
    #
class BaseScrollArea(QScrollArea):
    """
    滚动基础区域
    """
    def __init__(self,row,col,widgets:[]):
        container=QWidget(self)
        container_layout=QGridLayout()
        for i,w in enumerate(widgets):
            r=i//row
            c=i%col
            container_layout.addWidget(w,r,c)
        self.setWidget(container)

class CustomQPushButton(QPushButton):

    def __init__(self,label,row,parent:QTableWidget):
        super(CustomQPushButton, self).__init__(label)
        self.parent=parent
        self.row=row
        self.clicked.connect(self.operate)

    def operate(self):
        self.parent.removeRow(self.row)

class Table_ABC(QTableWidget):

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self.viewport())
        pen = QPen(QColor(0, 0, 0), 1, Qt.SolidLine)
        painter.setPen(pen)
        # 获取水平头标签的高度
        header_height = self.horizontalHeader().height()
        # 获取表格的宽度
        table_width = self.viewport().width()
        # 绘制横线
        painter.drawLine(0,0, table_width, 0)

    def add_buttons_to_cell(self, row, col, params):
        # 创建一个 QWidget 作为容器
        container = QWidget()
        # 创建一个 QHBoxLayout 来管理按钮布局
        layout = QHBoxLayout(container)
        # 遍历 params 列表，为每个 labor 创建一个 QPushButton 并添加到布局中
        for labor in params:
            button = QPushButton(labor)
            layout.addWidget(button)

        # 设置布局的方向和对齐方式
        layout.setContentsMargins(0, 0, 0, 0)  # 移除边距
        layout.setAlignment(Qt.AlignLeft)  # 按钮左对齐

        # 将容器设置为单元格的 widget
        self.setCellWidget(row, col, container)

    def get_data(self):
        # 获取表格的行数和列数
        rows = self.rowCount()
        columns = self.columnCount()
        # 用来存储表格内容的列表
        contents = []
        # 遍历每一行
        for row in range(rows):
            # 为当前行创建一个空列表
            row_data = []
            # 遍历每一列
            for column in range(columns):
                # 获取单元格中的项（QTableWidgetItem）
                widget=self.cellWidget(row,column)
                item = self.item(row, column)
                # 如果该单元格有数据，就添加到行数据列表中
                if item is not None:
                    # 使用 text() 方法获取文本内容
                    cell_content = item.text()
                    row_data.append(cell_content)
                elif widget is not None:
                    if isinstance(widget,QTextEdit):
                        html=widget.toHtml()
                        from src.backend.tools.file import parser_html_to_strs
                        content_list=parser_html_to_strs(html)
                        if content_list:
                            if re.match(r'^\d+$',content_list[0]):
                                text=' '.join(content_list[2:])
                            else:
                                text = ' '.join(content_list[1:])
                    elif isinstance(widget,QComboBox):
                        text=widget.currentIndex()+1 # QComboBox序列与数据库差1
                    elif isinstance(widget,QLineEdit):
                        text=widget.text()
                    else:
                        text=widget.toPlainText()
                    # 如果单元格为空，则可以添加空字符串或者其他默认值
                    row_data.append(text if text else '')
            # 将整行的数据添加到 contents 列表中
            contents.append(row_data)

        return contents

    def fill_data(self,df,params=[]):
         if self.rowCount() > 0:
             # 清空现有的表格内容
             self.clearContents()
         # 显示垂直头部（行号）
         self.verticalHeader().setVisible(False)
         self.setColumnCount(len(df.columns)+1)
         self.setHorizontalHeaderLabels(list(df.columns.values) + ['操作'])
         self.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)

         if len(df) > 0:
             # 设置表格的行数和列数
             self.setRowCount(len(df))
             for row in range(len(df)):
                 for col in range(len(df.columns)):
                     item = QTableWidgetItem()  # 转换为字符串
                     text = str(df.iat[row, col])
                     item.setData(Qt.UserRole,text)

                     if '.png' in text or '.jpg' in text:
                         parts=text.split(' ')
                         text=create_html(parts)
                         label = QTextEdit()
                         label.setHtml(text)
                         label.setFixedHeight(100)

                         self.setCellWidget(row,col,label)
                     else:
                         item.setText(text)
                         item.setToolTip(text)
                         item.setTextAlignment(Qt.AlignCenter)
                         self.setItem(row, col, item)

                 self.add_buttons_to_cell(row, col + 1, params)
         # 手动设置所有行的高度
         # for row in range(self.rowCount()):
         #     self.setRowHeight(row, 100)  # 设置每行高度为50像素
         # 自动调整所有列的宽度
         self.resizeColumnsToContents()
         self.resizeRowsToContents()


def get_main_window():
    if 'main' not in tables.keys():
        raise ValueError("Main window class not registered.")
    global MAIN_WINDOW
    if not MAIN_WINDOW:
        MAIN_WINDOW = tables['main']()
    return MAIN_WINDOW

# import pandas as pd
# # 创建一个简单的字典来存储数据
# data = {
#     'Name': ['Alice', 'Bob', 'Charlie'],
#     'Age': [25, 30, 35],
#     'City': ['Beijing', 'Shanghai', 'Guangzhou']
# }
# df = pd.DataFrame(data)
# print(list(df.columns.values)+['操作'])
# print()